<template>
    <div class='edit-popup'>
        <popup
            ref='popupRef'
            :title='popupTitle'
            :async='true'
            width='750px'
            @confirm='handleSubmit'
            @close='handleClose'
        >
            <el-form ref='formRef' :model='formData' label-width='100px' :rules='formRules'>
                <el-form-item label='等级名称' prop='name'>
                    <el-input v-model='formData.name' clearable placeholder='请输入等级名称' />
                </el-form-item>
                <el-form-item label='所需里程' prop='licheng'>
                    <el-input v-model='formData.licheng' clearable placeholder='请输入升级所需里程' />
                </el-form-item>
                <el-form-item label='封面图' prop='fengmian_image'>
                    <!--                    <el-input v-model="formData.fengmian_image" clearable placeholder="请输入封面图" />-->
                    <material-picker :limit='1' v-model='formData.fengmian_image' type='image' />
                </el-form-item>
                <el-form-item label='权益图' prop='quanyi_image'>
                    <material-picker :limit='1' v-model='formData.quanyi_image' type='image' />
                    <!--                    <el-input v-model="formData.quanyi_image" clearable placeholder="请输入权益图" />-->
                </el-form-item>
                <el-form-item label='等级图标' prop='dengji_icon_image'>
                    <material-picker :limit='1' v-model='formData.dengji_icon_image' type='image' />
                    <!--                    <el-input v-model="formData.dengji_icon_image" clearable placeholder="请输入等级icon图标" />-->
                </el-form-item>
                <el-form-item label='赠送优惠券' prop='coupon_json'>
                    <div class='coupon-list'>
                        <div class='coupon-item' v-for='(couponItem,couponIndex) in formData.coupon_json'
                             :key='couponIndex'>
                            <el-form-item label-width='70px' label='优惠券'>
                                <el-select v-model='couponItem.coupon' style='width: 180px;'>
                                    <el-option
                                        v-for='(opt,optIndex) in couponList'
                                        :key='optIndex'
                                        :label='opt.label'
                                        :value='opt.value'
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item label-width='70px' label='数量'>
                                <el-input
                                    v-model='couponItem.count'
                                    placeholder='请输入数量'
                                    type='number'
                                    :min='1'
                                />
                            </el-form-item>
                            <el-button link type='danger' @click='deleteCoupon(couponIndex)'>删除</el-button>
                        </div>
                    </div>

                    <el-button type='primary' @click='chooseCouponHandler'>添加优惠券</el-button>
                    <!--                    <el-input v-model="formData.coupon_json" clearable placeholder="请输入赠送优惠券" />-->
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang='ts' setup name='levelconfigEdit'>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiLevelconfigAdd, apiLevelconfigEdit, apiLevelconfigDetail } from '@/api/levelconfig'
import { timeFormat } from '@/utils/util'
import { apiDiscountCouponLists } from '@/api/discount_coupon'

import type { PropType } from 'vue'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const couponList = ref([])
const getAllCoupon = async () => {
    const resp = await apiDiscountCouponLists({
        page_no: 1,
        page_size: 2500
    })
    couponList.value = resp.lists.map((item: any) => {
        const { title, id } = item
        return {
            label: title,
            value: id
        }
    })
    console.log(couponList.value, '优惠券列表')
}
getAllCoupon()

const deleteCoupon = (index) => {
    formData.coupon_json.splice(index, 1)
}

function chooseCouponHandler() {
    formData.coupon_json.push({ coupon: '', count: 1 })
}

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑等级配置表' : '新增等级配置表'
})

// 表单数据
const formData = reactive({
    id: '',
    name: '',
    licheng: '',
    fengmian_image: '',
    quanyi_image: '',
    dengji_icon_image: '',
    coupon_json: []
})


// 表单验证
const formRules = reactive<any>({
    licheng: [{
        required: true,
        message: '请输入升级所需里程',
        trigger: ['blur']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }


}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiLevelconfigDetail({
        id: row.id
    })
    if (!data.coupon_json) {
        data.coupon_json = []
    } else {
        data.coupon_json = JSON.parse(data.coupon_json)
    }
    setFormData(data)
    open('edit')
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const{coupon_json} = formData
    const data = { ...formData }
    if (coupon_json && coupon_json.length){
        data.coupon_json = JSON.stringify(coupon_json)
    }
    mode.value == 'edit'
        ? await apiLevelconfigEdit(data)
        : await apiLevelconfigAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>

<style lang='scss' scoped>
.coupon-list {
    .coupon-item {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        &:last-child{
        }
    }
}
</style>
